#include <stdio.h>
#include <time.h>
#include <nuttx/pthread.h>
#include "Mutex.h"

Mutex::Mutex() : mutex_(new pthread_mutex_s()) {
	pthread_mutexattr_s attr;
	pthread_mutexattr_init(&attr);
	pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
	pthread_mutex_init(mutex_, &attr);
}

Mutex::~Mutex() {
	pthread_mutex_destroy(mutex_);
	delete mutex_;
}

bool Mutex::lock(uint32_t timeout) {
#if 0 // there is no timedlock support in Nuttx
	if (timeout == ~0UL)
		return pthread_mutex_lock(mutex_) == 0;
	else {
		timespec time;
		clock_gettime(CLOCK_REALTIME, &time);
		time.tv_sec += timeout / 1000;
		time.tv_nsec += (timeout % 1000) * 1000000;
        if (time.tv_nsec >= 1000000000) {
        	++time.tv_sec;
        	time.tv_nsec -= 1000000000;
        }

		return pthread_mutex_timedlock(mutex_, &time) == 0;
	}
#else
	return pthread_mutex_lock(mutex_) == 0;
#endif
}

void Mutex::unlock() {
	pthread_mutex_unlock(mutex_);
}


